/**
 * This file is part of Idegen, the application to create IDE project files.
 *
 * @copyright Copyright (c) 2011-2012, Walter Tamboer http://waltertamboer.nl
 * @file Idegen/Idegen/IdegenSourceSet.cpp
 */

#include "Idegen/PrecompiledHeader.hpp"
#include "Idegen/Application/Settings.hpp"
#include "Idegen/IO/File.hpp"
#include "Idegen/IO/FileSystem.hpp"
#include "Idegen/Idegen/IdegenProjectFile.hpp"
#include "Idegen/Idegen/IdegenProjectFilter.hpp"
#include "Idegen/Idegen/IdegenSourceSet.hpp"

namespace Idegen
{
	IdegenSourceSet::IdegenSourceSet()
		: IdegenProjectFilter( "" )
	{
	}

	IdegenSourceSet::~IdegenSourceSet()
	{
	}

	void IdegenSourceSet::ParseDirectory( IdegenProjectFilter* filter, Settings* settings, TiXmlElement* element )
	{
		std::string path;
		if ( ParseAttributeString( element, "path", path ) )
		{
			int depth = 0;
			if ( !ParseAttributeInt( element, "depth", depth ) )
			{
				depth = -1;
			}

			const std::string basePath = settings->GetBasePath();
			const std::string fullPath = RelativeToAbsolutePath( path, basePath, true );
			const FileList files = Idegen::GetFiles( fullPath, depth );

			for ( FileList::const_iterator it = files.begin(); it != files.end(); ++it )
			{
				filter->AddFile( new IdegenProjectFile( *it, filter ) );
			}
		}
	}

	void IdegenSourceSet::ParseElement( IdegenProjectFilter* filter, Settings* settings, TiXmlElement* parent )
	{
		TiXmlElement* element = parent->FirstChildElement();
		while ( element != NULL )
		{
			const std::string elementName = element->Value();
			
			if ( elementName == "i:directory" )
			{
				ParseDirectory( filter, settings, element );
			}
			else if ( elementName == "i:file" )
			{
				ParseFile( filter, settings, element );
			}
			else if ( elementName == "i:filter" )
			{
				ParseFilter( filter, settings, element );
			}

			element = element->NextSiblingElement();
		}
	}

	void IdegenSourceSet::ParseFile( IdegenProjectFilter* filter, Settings* settings, TiXmlElement* element )
	{
		settings;
		std::string path;

		if ( ParseAttributeString( element, "path", path ) )
		{
			if ( FileExists( path ) )
			{
				AddFile( new IdegenProjectFile( File( path ), filter ) );
			}
		}
	}

	void IdegenSourceSet::ParseFilter( IdegenProjectFilter* filter, Settings* settings, TiXmlElement* element )
	{
		std::string name;
		
		ParseAttributeString( element, "name", name );

		IdegenProjectFilter* child = AddFilter( name, filter );

		ParseElement( child, settings, element );
	}

	void IdegenSourceSet::Unserialize( Settings* settings, TiXmlElement* parent )
	{
		ParseElement( this, settings, parent );
	}
}
